//可选通道展示表格
<template>
  <div class="segment-list-box">
    <el-table
      v-if="tableHead.length"
      ref="segmentTable"
      border
      :data="segmentList"
      style="width: 100%"
      :max-height="360"
      size="mini"
      :span-method="objectSpanMethod"
    >
      <template slot="empty">
        <NullData />
      </template>
      <el-table-column
        v-if="showCheckBox"
        fixed="left"
        width="50"
        align="center"
        :resizable="false"
      >
        <template v-slot="scope">
          <el-checkbox v-model="scope.row.checked" @change="changeSelected(scope.row)" />
        </template>
      </el-table-column>
      <el-table-column
        v-else
        type="index"
        fixed="left"
        :label="$t('SEQUENCE')"
        :width="resetSize(60)"
        align="center"
        :resizable="false"
      />
      <el-table-column
        v-if="(operateType === 'open' || operateType === 'restore') && type !== 'configed'"
        :label="$t('OPTIMAL_CASE')"
        fixed="left"
        width="110"
        prop="channelType"
        align="center"
        :resizable="false"
      >
        <template v-slot="scope">
          {{ scope.row.channelType === 'LOSS' ? $t('CHAIN_LOSS_MINIMUM') : $t('TIME_LESS') }}
        </template>
      </el-table-column>
      <el-table-column
        :label="$t('LINK_LOSS')"
        fixed="left"
        width="110"
        prop="loss"
        align="center"
        :resizable="false"
      >
        <template v-slot="scope">
          {{ scope.row.loss > 990000 ? '--' : changeDecimal(scope.row.loss, 3) }}
        </template>
      </el-table-column>
      <el-table-column
        v-if="type !== 'configed' && showType !== 'selected'"
        :label="$t('FIBER_TOTAL_TIME')"
        fixed="left"
        width="120"
        prop="cutoverTime"
        align="center"
        :resizable="false"
      >
        <template v-slot="scope">
          {{ scope.row.cutoverTime > 999999 || 0 > scope.row.cutoverTime ? '--' : scope.row.cutoverTime }}
        </template>
      </el-table-column>
      <el-table-column
        v-if="type !== 'configed' && showType !== 'selected'"
        :label="$t('USED_TIME')"
        fixed="left"
        width="80"
        prop="cutoverNum"
        align="center"
        :resizable="false"
      />
      <div v-for="(item, index) in tableHead" :key="index">
        <el-table-column
          :label="item.segmentName"
          align="center"
          show-overflow-tooltip
          :render-header="tableRenderHeader"
          width="220"
          :resizable="false"
        >
          <el-table-column
            :label="item.startNode.nodeName"
            align="center"
            :prop="`segmentList${index}.startPort.bizName`"
            :render-header="tableRenderHeader"
            show-overflow-tooltip
            min-width="110"
            :resizable="false"
          >
            <template v-slot="scope">
              <div
                v-if="hasLogicSegment(scope.row[`segmentList${index}`]) && operateType !== 'view'"
                class="relative"
              >
                <!-- 实际显示 -->
                <div
                  slot="reference"
                  class="flex justify-between align-center text-holder channel-item no-wrap"
                >
                  <span class="flex-1">
                    {{ scope.row[`segmentList${index}`].startPort.bizName }}
                  </span>
                  <span v-if="scope.row[`segmentList${index}`].fiber">
                    {{ scope.row[`segmentList${index}`].fiber.fiberName }}
                  </span>
                  <span class="flex-1">
                    {{ scope.row[`segmentList${index}`].endPort.bizName }}
                  </span>
                </div>
                <!-- select框实例 -->
                <el-select
                  v-model="scope.row[`segmentList${index}`].channelId"
                  @change="
                    channelChange(
                      amongChannel[scope.row[`segmentList${index}`].segmentId],
                      scope.row[`segmentList${index}`].channelId,
                      scope.$index
                    )
                  "
                >
                  <el-option
                    v-for="channel in amongChannel[scope.row[`segmentList${index}`].segmentId]"
                    :key="channel.channelId"
                    :value="channel.channelId"
                    label=" "
                    :disabled="
                      segmentList.some(
                        i =>
                          i[`segmentList${index}`].channelId === channel.channelId &&
                          i.startPortId !== scope.row.startPortId &&
                          i.channelType === scope.row.channelType
                      )
                    "
                  >
                    <div class="flex justify-between align-center channel-item">
                      <span class="flex-1" :title="channel.startPort.bizName">
                        {{ channel.startPort.bizName }}
                      </span>
                      <span v-if="channel.fiber" :title="channel.fiber.fiberName">
                        {{ channel.fiber.fiberName }}
                      </span>
                      <span class="flex-1" :title="channel.endPort.bizName">
                        {{ channel.endPort.bizName }}
                      </span>
                    </div>
                  </el-option>
                </el-select>
              </div>
              <span v-else>
                {{
                  scope.row[`segmentList${index}`]
                    ? scope.row[`segmentList${index}`].startPort.bizName
                    : '--'
                }}
              </span>
            </template>
          </el-table-column>
          <el-table-column
            v-if="item.cable"
            :label="item.cable.cableName"
            :prop="`segmentList${index}.fiber.fiberName`"
            :render-header="tableRenderHeader"
            align="center"
            show-overflow-tooltip
            min-width="110"
            :resizable="false"
          >
            <template v-slot="scope">
              {{
                scope.row[`segmentList${index}`].fiber
                  ? scope.row[`segmentList${index}`].fiber.fiberName
                  : '--'
              }}
            </template>
          </el-table-column>
          <el-table-column
            :label="item.endNode.nodeName"
            align="center"
            :prop="`segmentList${index}.endPort.bizName`"
            :render-header="tableRenderHeader"
            show-overflow-tooltip
            min-width="110"
            :resizable="false"
          >
            <template v-slot="scope">
              {{
                scope.row[`segmentList${index}`]
                  ? scope.row[`segmentList${index}`].endPort.bizName
                  : '--'
              }}
            </template>
          </el-table-column>
        </el-table-column>
      </div>
      <el-table-column
        v-if="showCutoverList"
        :label="$t('TRANSFER_DETAIL')"
        width="200"
        fixed="right"
        prop="cutoverList"
      >
        <template v-slot="scope">
          {{ cutoverDesc(scope.row) }}
        </template>
      </el-table-column>
      <template v-if="operateType === 'back' || showType === 'selected'">
        <el-table-column
          v-if="showType !== 'main'"
          :label="$t('STANDBY_MODE')"
          width="120"
          fixed="right"
          prop="exclusive"
        >
          <template v-slot="scope">
            <el-select v-model="scope.row.exclusive" :disabled="showType === 'selected'">
              <el-option
                v-for="item in dictList.STANDBY_MODE"
                :key="item.value"
                :value="item.value"
                :label="item.label"
              />
            </el-select>
          </template>
        </el-table-column>
        <el-table-column
          v-if="showType !== 'main' && operateType !== 'restore' && operateType !== 'view'"
          :label="$t('OPERATE')"
          :width="resetSize(70)"
          fixed="right"
          class-name="operate-cell"
          prop="operate"
        >
          <template v-slot="scope">
            <el-button
              v-if="showType === 'selected'"
              type="text"
              size="mini"
              icon="el-icon-delete"
              @click="delBack(scope.row, scope.$index)"
            >{{ $t('DEL') }}</el-button>
            <el-button
              v-else
              type="text"
              size="mini"
              icon="el-icon-circle-check"
              :disabled="getBackDisabled(scope.row, scope.$index)"
              @click="addBack(scope.row, scope.$index)"
            >{{ $t('SAVE') }}</el-button>
          </template>
        </el-table-column>
      </template>
    </el-table>
  </div>
</template>
<script>
  import { mapGetters } from 'vuex'
  import backChannelApi from '@/api/oen/BackChannelApi'
  import recomApi from '@/api/oen/RecomApi'
  import { changeDecimal, tableRenderHeader } from '@/utils/common'

  export default {
    name: 'SegmentDetail',
    props: {
      operateType: {
        type: String,
        default: 'view'
      },
      type: {
        type: String,
        default: ''
      },
      bizType: {
        type: String,
        default: ''
      },
      showType: {
        type: String,
        default: ''
      },
      rowData: {
        type: Object,
        default: () => {
          return {
            segmentList: [],
            channel: {},
            channelList: []
          }
        }
      },
      formData: {
        type: Object,
        default: () => {}
      },
      backChannelIdList: {
        type: Array,
        default: () => []
      },
      showCheckBox: {
        type: Boolean,
        default: true
      },
      showCutoverList: {
        type: Boolean,
        default: true
      }
    },
    data() {
      return {
        changeDecimal: changeDecimal
      }
    },
    computed: {
      ...mapGetters(['dictList']),
      tableHead() {
        return this.rowData.segmentList || []
      },
      segmentList() {
        return (
          (this.formData.routeData && this.operateType === 'view'
            ? this.formData.channelData
            : this.rowData.channelList) || []
        )
      },
      amongChannel() {
        return this.rowData.amongChannel || {}
      },
      baseAmong() {
        return this.rowData.baseAmong || []
      }
    },
    created() {},
    methods: {
      tableRenderHeader(h, data) {
        return tableRenderHeader(h, data)
      },
      // 可选网段改变事件
      channelChange(channelList, channelId, rowIndex) {
        const curChannel = channelList.find(i => i.channelId === channelId)
        const logicSegment = this.baseAmong.find(i => i.segmentId === curChannel.logicSegmentId)
        const curLink = this.segmentList[rowIndex]
        // 更新网段信息
        curLink.segmentList.forEach((i, segmentIndex) => {
          const physicStruct = logicSegment.physicStruct.find(
            j => j.segmentId === i.segmentId && i.segmentSort === logicSegment.segmentSort
          )
          if (physicStruct) {
            physicStruct.segmentSort = i.segmentSort
            i = { ...physicStruct }
            curLink.segmentList[segmentIndex] = { ...physicStruct }
            curLink[`segmentList${segmentIndex}`] = { ...physicStruct }
          }
        })
        // 更新逻辑网段信息
        curLink.physicSegmentList.forEach((i, index) => {
          if (i.segmentSort === logicSegment.segmentSort) {
            curLink.physicSegmentList[index] = logicSegment
          }
        })
        // console.log('logicSegment', logicSegment)
        // console.log('curLink', curLink)
        this.getCutoverList(curLink)
      },
      // 获取割接信息
      async getCutoverList(data) {
        data.isReach = false
        const res = await recomApi.logicChannelAnalyze(data.physicSegmentList)
        data.isReach = true
        data.cutoverList = res.cutoverList || []
        data.cutoverNum = res.cutoverNum
        data.cutoverTime = res.cutoverTime
        data.loss = res.loss
      },
      // 可选择网段表格合并
      objectSpanMethod({ row, column, rowIndex }) {
        if (this.operateType !== 'view' && column.property) {
          const key = column.property.split('.')[0]
          const key2 = column.property.split('.')[1] || null
          // console.log('row[key]', key)
          // 业务开通合并最优方案单元格
          if (
            (this.operateType === 'open' || this.operateType === 'restore') &&
            key === 'channelType' &&
            this.formData.aPortData2 &&
            this.formData.aPortData2.portId
          ) {
            return rowIndex % 2 === 0 ? [2, 1] : [0, 0]
          }
          return this.isStartPort(key, key2, row)
        }
        return this.isColumnOperateExclusive(column)
      },
      isStartPort(key, key2, row) {
        if (key && row[key] && this.hasLogicSegment(row[key])) {
          if (key2 && key2 === 'startPort') {
            return row[key].fiber ? [1, 3] : [1, 2]
          } else {
            return [0, 0]
          }
        }
      },
      isColumnOperateExclusive(column) {
        if (
          (column.property === 'operate' || column.property === 'exclusive') &&
          this.formData.aPortData2 &&
          this.formData.aPortData2.portId
        ) {
          return [2, 1]
        }
      },
      // 判断是否有可选逻辑网段
      hasLogicSegment(row) {
        const amongChannel = this.amongChannel[row.segmentId]
        return amongChannel && row.segmentSort && row.segmentSort === amongChannel[0].segmentSort
      },
      // 割接信息展示
      cutoverDesc(row) {
        // console.log('row', row)
        if (!row.cutoverList) return ''
        const desc = []
        row.cutoverList.forEach(i => {
          const str = this.$t('PORT_CONNECT_LINK', {
            msg1: i.deviceName,
            msg2: i.port.bizName,
            msg3: i.connPort.bizName
          })
          desc.push(str)
        })
        return desc.join('；') || this.$t('NO_PIPETTING_IS_REQUIRED')
      },
      // 通道选中状态
      changeSelected(row) {
        console.log(row)
        if (this.type === 'configed') {
          this.$emit('configedSelected', {
            routeData: this.rowData,
            channelData: row
          })
          return
        }
        const checked = row.checked
        this.formData.routeData &&
          this.formData.channelData.forEach(i => {
            i.checked = false
          })
        if (checked) {
          // 选中状态保存通道和链路信息
          this.formData.selectedType = 'recommend'
          this.formData.channelData = this.segmentList.filter(
            i => i.channelType === row.channelType
          )
          this.formData.channelData.forEach(i => {
            i.checked = checked
          })
          this.formData.routeData = this.rowData
        } else {
          this.formData.selectedType = ''
          // 非选中状态删除已保存通道和链路信息
          this.formData.selectedType = ''
          this.formData.routeData = null
          this.formData.channelData = []
        }
      },
      async checkBackup(sIndex) {
        const firstData = this.segmentList[sIndex]
        const checkResult = { canNext: true }
        // 独占备用不能选择共享的通道
        if (firstData.exclusive === 'EXCLUSIVE') {
          const shareChannel = []
          firstData.segmentList.forEach((i, index) => {
            if (i.status === 'BACKUP') {
              shareChannel.push({
                segmentId: this.tableHead[index].segmentId,
                segmentName: this.tableHead[index].segmentName,
                first: i.channelId,
                second: ''
              })
            }
          })
          if (this.formData.aPortData2 && this.formData.aPortData2.portId) {
            const secondData = this.segmentList[sIndex + 1]
            secondData.segmentList.forEach((i, index) => {
              if (i.status === 'BACKUP') {
                const shareData = shareChannel.find(
                  j => j.segmentId === this.tableHead[index].segmentId
                )
                if (shareData) {
                  shareData.second = i.channelId
                } else {
                  shareChannel.push({
                    segmentId: this.tableHead[index].segmentId,
                    segmentName: this.tableHead[index].segmentName,
                    first: i.channelId,
                    second: ''
                  })
                }
              }
            })
          }
          console.log('shareChannel', shareChannel)
          const segmentChannelIds = []
          shareChannel.forEach(i => {
            segmentChannelIds.push(i.first)
            i.second && segmentChannelIds.push(i.second)
          })
          if (segmentChannelIds.length === 0) {
            return checkResult
          }
          const result = await backChannelApi.linkBizNameBySegmentChannelId({
            segmentChannelIds: segmentChannelIds.join()
          })
          let msg = ''
          shareChannel.forEach(i => {
            msg +=
              this.$t('CHANNEL_CONFIGED_SHARE', {
                msg1: i.segmentName,
                msg2: 1,
                msg3: result[i.first].join()
              }) + ' <br/> '
            i.second &&
              (msg +=
                this.$t('CHANNEL_CONFIGED_SHARE', {
                  msg1: i.segmentName,
                  msg2: 2,
                  msg3: result[i.second].join()
                }) + ' <br/> ')
          })
          checkResult.canNext = false
          checkResult.msg = msg + this.$t('DELETE_AND_CONFIG')
        }
        return checkResult
      },
      // 添加备用路由
      async addBack(row, index) {
        const checkBackup = await this.checkBackup(index)
        if (!checkBackup.canNext) {
          this.$alert(checkBackup.msg, {
            dangerouslyUseHTMLString: true,
            customClass: 'check-confirm'
          })
          return
        }
        this.$confirm(this.$t('CONFIRM_BACK'), { type: 'warning' })
          .then(() => {
            const segmentBoList = row.segmentList.map(i => {
              return {
                cableId: i.fiberId,
                endNodeId: i.endNodeId,
                segmentChannelId: i.channelId,
                segmentId: i.segmentId,
                startNodeId: i.startNodeId
              }
            })
            const queryData = [
              {
                bizChannelId: this.formData.mainChannelList[0].bizChannelId,
                bizId: this.formData.bizId,
                bizName: this.formData.bizName,
                exclusive: row.exclusive === 'EXCLUSIVE',
                segmentIdList: this.rowData.segmentList.map(i => i.segmentId),
                segmentBoList: segmentBoList
              }
            ]
            if (this.formData.aPortData2 && this.formData.aPortData2.portId) {
              const secondData = this.segmentList[index + 1]
              const secondSegmentBoList = secondData.segmentList.map(i => {
                return {
                  cableId: i.fiberId,
                  endNodeId: i.endNodeId,
                  segmentChannelId: i.channelId,
                  segmentId: i.segmentId,
                  startNodeId: i.startNodeId
                }
              })
              queryData.push({
                bizChannelId: this.formData.mainChannelList[1].bizChannelId,
                bizId: this.formData.bizId,
                exclusive: row.exclusive === 'EXCLUSIVE',
                segmentIdList: this.rowData.segmentList.map(i => i.segmentId),
                segmentBoList: secondSegmentBoList
              })
            }
            backChannelApi.add(queryData).then(res => {
              if (res) {
                this.$message.success(this.$t('SAVE_SUCCESS'))
                this.$emit('reload')
                if (this.formData.aPortData2 && this.formData.aPortData2.portId) {
                  this.rowData.channelList.splice(index, 2)
                } else {
                  this.rowData.channelList.splice(index, 1)
                }
                this.rowData.channelList.length === 0 && this.$emit('delRow', this.rowData)
              }
            })
          })
          .catch(() => {})
      },
      // 删除备用
      delBack(row, index) {
        this.$confirm(this.$t('CONFIRM_DELETE_BACKUP'), { type: 'warning' })
          .then(() => {
            const backIds = [row.backId]
            if (this.formData.aPortData2 && this.formData.aPortData2.portId) {
              const secondData = this.segmentList[index + 1]
              backIds.push(secondData.backId)
            }
            backChannelApi.batchDel({
              backIds: backIds.join(),
              bizName: this.formData.bizName // 操作日志需要存业务名称
            }).then(res => {
              if (res) {
                this.$message.success(this.$t('DELETE_SUCCESS'))
                this.$emit('reload')
              }
            })
          })
          .catch(() => {})
      },
      getBackDisabled(row, index) {
        const disabled = this.backChannelIdList.some(
          i => row.segmentList.map(j => j.id).join() === i
        )
        let second = false
        if (this.formData.aPortData2 && this.formData.aPortData2.portId) {
          const secondData = this.segmentList[index + 1] || null
          if (secondData) {
            second = this.backChannelIdList.some(
              i => secondData.segmentList.map(j => j.id).join() === i
            )
          }
        }
        return disabled || second
      }
    }
  }
</script>
<style lang="scss">
  .check-confirm {
    max-width: 80%;
    width: auto !important;
  }
  .channel-item {
    height: 100%;

    &.text-holder {
      position: absolute;
      width: 100%;
      height: 28px;
      padding: 0 30px 0 5px;
      z-index: 2;
      pointer-events: none;
    }

    span {
      width: 33%;
      line-height: 16px;
      text-align: center;
      overflow: hidden;
      text-overflow: ellipsis;
    }
  }
</style>
